package Controller

import (
	"back_go/DAO/gorm"
	"back_go/DAO/gorm/GormModel"
	"back_go/Response"
	"github.com/gin-gonic/gin"
	"github.com/jinzhu/copier"
	"math"
	"strconv"
	"time"
)

type ProdCommUser struct {
	ProdCommID  uint64  `gorm:"column:prod_comm_id" json:"prodCommId"`
	Score       int     `gorm:"column:score" json:"score"`
	IsAnonymous int     `gorm:"column:is_anonymous" json:"isAnonymous"`
	Status      *int    `gorm:"column:status" json:"status,omitempty"`
	RecTime     *string `gorm:"column:rec_time" json:"recTime,omitempty"`     // 改为*string
	ReplyTime   *string `gorm:"column:reply_time" json:"replyTime,omitempty"` // 改为*string
	Evaluate    *int    `gorm:"column:evaluate" json:"evaluate,omitempty"`
	NickName    *string `gorm:"column:nick_name" json:"nickName,omitempty"`
	UserMobile  *string `gorm:"column:user_mobile" json:"userMobile,omitempty"`
	ProdName    string  `gorm:"column:prod_name" json:"prodName"`
}
type UpdateCommReq struct {
	ProdCommId   int       `json:"prodCommId"`
	ProdId       int       `json:"prodId"`
	OrderItemId  int       `json:"orderItemId"`
	UserId       string    `json:"userId"`
	Content      string    `json:"content"`
	RecTime      time.Time `json:"recTime"`
	ReplyTime    time.Time `json:"replyTime"`
	Score        int       `json:"score"`
	Pics         string    `json:"pics"`
	IsAnonymous  int       `json:"isAnonymous"`
	Status       int       `json:"status"`
	ReplyContent string    `json:"replyContent"`
}

type ProductQuery struct {
	ProdName *string `form:"prodName"`
	Status   *int    `form:"status"`
}

func GetProdCommPage(c *gin.Context) {
	var query ProductQuery
	_ = c.ShouldBindQuery(&query)

	// 分页参数处理
	currentStr := c.Query("current")
	sizeStr := c.Query("size")
	page, err := strconv.Atoi(currentStr)
	if err != nil || page < 1 {
		page = 1
	}

	size, err := strconv.Atoi(sizeStr)
	if err != nil || size < 1 {
		size = 10
	}

	// 初始化查询构建器
	db := gorm.Db.Table("tz_prod_comm as pc").
		Select("pc.prod_comm_id, pc.score, pc.is_anonymous, pc.status, " +
			"DATE_FORMAT(pc.rec_time, '%Y-%m-%d %H:%i:%s') as rec_time, " + // 格式化时间
			"DATE_FORMAT(pc.reply_time, '%Y-%m-%d %H:%i:%s') as reply_time, " +
			"pc.evaluate, u.nick_name, u.user_mobile, p.prod_name").
		Joins("LEFT JOIN tz_prod p ON p.prod_id = pc.prod_id").
		Joins("LEFT JOIN tz_user u ON u.user_id = pc.user_id")

	// 动态条件处理
	if query.Status != nil {
		db = db.Where("pc.status = ?", *query.Status)
	}
	if query.ProdName != nil && *query.ProdName != "" {
		db = db.Where("p.prod_name LIKE ?", "%"+*query.ProdName+"%")
	}

	// 获取总数
	var count int64
	if err := db.Count(&count).Error; err != nil {
		c.JSON(200, Response.ResponseBody{
			Code:    "A00005",
			Data:    nil,
			Success: true,
			Msg:     "服务器出了点小差",
		})
		return
	}

	// 分页查询
	offset := (page - 1) * size
	var prodCommUsers []ProdCommUser
	if err := db.Limit(size).Offset(offset).Find(&prodCommUsers).Error; err != nil {
		c.JSON(200, Response.ResponseBody{
			Code:    "A00005",
			Data:    nil,
			Success: true,
			Msg:     "服务器出了点小差",
		})
		return
	}

	//处理匿名情况，值引用而不是 改变副本
	for i := range prodCommUsers {
		if prodCommUsers[i].IsAnonymous == 1 {
			*prodCommUsers[i].NickName = "匿名用户"
		}
	}
	c.JSON(200, Response.ResponseBody{
		Code: "00000",
		Data: PageParam1[ProdCommUser]{
			Current: page,
			Total:   count,
			Size:    size,
			Records: prodCommUsers,
			Pages:   int(math.Ceil(float64(count) / float64(size))),
		},
		Success:   true,
		Msg:       nil,
		Version:   "1.0",
		Timestamp: time.Now().Unix(),
	})
}

/*
GetProdCommById
@Description: 根据id查询评论
*/
func GetProdCommById(c *gin.Context) {
	id := c.Param("infoId")
	db := gorm.Db
	var prodComm GormModel.TzProdComm
	db.First(&prodComm, id)
	c.JSON(200, Response.ResponseBody{
		Code:      "00000",
		Msg:       nil,
		Data:      prodComm,
		Version:   "V1.0",
		Timestamp: time.Now().Unix(),
		Sign:      nil,
		Success:   true,
	})

}

/*
UpdateProdComm
@Description: 商家回复
*/
func UpdateProdComm(c *gin.Context) {
	var updateCommReq UpdateCommReq
	_ = c.ShouldBindJSON(&updateCommReq)
	var prodComm GormModel.TzProdComm
	err := copier.CopyWithOption(&prodComm, &updateCommReq, copier.Option{IgnoreEmpty: true, DeepCopy: true})
	prodComm.ReplyTime = time.Now()
	db := gorm.Db.Begin()
	// 开启事务 defer 回滚
	defer func() {
		if r := recover(); r != nil {
			db.Rollback()
			c.JSON(200, Response.ResponseBody{
				Code:    "A00005",
				Data:    nil,
				Success: true,
				Msg:     "服务器出了点小差",
			})
		} else if err != nil {
			db.Rollback()
		} else {
			db.Commit()
		}
	}()

	db.Save(&prodComm)
	c.JSON(200, Response.ResponseBody{
		Code:      "00000",
		Msg:       nil,
		Data:      true,
		Success:   true,
		Version:   "V1.0",
		Timestamp: time.Now().Unix(),
	})
}
